<!DOCTYPE html>
<html>
<head>
    <title>教师页面</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 1200px;
            margin: 0 auto;
            padding: 20px;
            background-color: #f0f2f5;
        }
        .header {
            text-align: center;
            margin-bottom: 30px;
            color: #333;
        }
        .groups-container {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(400px, 1fr));
            gap: 15px;
            margin: 15px 0;
            width: 100%;
        }
        .group-card {
            padding: 15px;
            border: 1px solid #ddd;
            border-radius: 10px;
            background-color: white;
            box-shadow: 0 2px 4px rgba(0,0,0,0.1);
            width: 100%;
            box-sizing: border-box;
        }
        .delete-btn {
            padding: 4px 8px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 12px;
            transition: background-color 0.2s;
            margin-left: 8px;
        }
        .delete-btn:hover {
            background-color: #ff7875;
        }
        .member-item {
            display: flex;
            align-items: center;
            padding: 4px 8px;
            margin-bottom: 2px;
            width: 100%;
            background-color: #fafafa;
            border-radius: 4px;
        }
        .start-class-btn {
            position: fixed;
            bottom: 20px;
            right: 20px;
            padding: 15px 30px;
            background-color: #1a73e8;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.2s;
        }
        .start-class-btn:hover {
            background-color: #1557b0;
        }
        .question-form {
            position: fixed;
            bottom: 20px;
            left: 20px;
            padding: 20px;
            background-color: white;
            border-radius: 10px;
            box-shadow: 0 2px 8px rgba(0,0,0,0.1);
            width: 300px;
        }
        
        .question-form textarea,
        .question-form input {
            width: 100%;
            padding: 8px;
            margin-bottom: 10px;
            border: 1px solid #ddd;
            border-radius: 4px;
        }
        
        .question-form button {
            background-color: #4CAF50;
            color: white;
            padding: 10px 20px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
        }
        
        .student-name {
            font-size: 14px;
            margin-right: 8px;
            white-space: nowrap;
            min-width: 60px;
        }

        .student-answers {
            display: flex;
            flex-wrap: nowrap;
            gap: 2px;
            flex: 1;
            overflow-x: visible;
        }

        .student-answer {
            display: inline-block;
            padding: 2px 6px;
            margin: 0 1px;
            border-radius: 2px;
            font-size: 12px;
            min-width: 20px;
            text-align: center;
        }

        .student-answer.correct {
            background-color: #52c41a;
            color: white;
        }

        .student-answer.incorrect {
            background-color: #ff4d4f;
            color: white;
        }

        .student-answer.unanswered {
            background-color: #d9d9d9;
            color: rgba(0, 0, 0, 0.65);
        }

        .members-list {
            width: 100%;
        }

        .publish-questions-btn {
            padding: 15px 30px;
            background-color: #1890ff;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.2s;
        }

        .publish-questions-btn:hover {
            background-color: #40a9ff;
        }

        .questions-dialog {
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            background-color: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 4px 12px rgba(0,0,0,0.15);
            z-index: 1000;
            width: 400px;
            display: none;
        }

        .dialog-overlay {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            z-index: 999;
            display: none;
        }

        .questions-dialog h2 {
            margin-top: 0;
            margin-bottom: 20px;
        }

        .questions-dialog .input-group {
            margin-bottom: 20px;
        }

        .questions-dialog input {
            width: 100%;
            padding: 8px;
            border: 1px solid #ddd;
            border-radius: 4px;
            font-size: 16px;
        }

        .dialog-buttons {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
        }

        .dialog-btn {
            padding: 8px 16px;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 14px;
        }

        .dialog-btn.cancel {
            background-color: #f5f5f5;
            color: #666;
        }

        .dialog-btn.confirm {
            background-color: #1890ff;
            color: white;
        }

        .dialog-btn:hover {
            opacity: 0.8;
        }

        .clear-all-btn {
            position: fixed;
            bottom: 20px;
            right: 200px;
            padding: 15px 30px;
            background-color: #ff4d4f;
            color: white;
            border: none;
            border-radius: 25px;
            cursor: pointer;
            font-size: 16px;
            box-shadow: 0 2px 5px rgba(0,0,0,0.2);
            transition: background-color 0.2s;
        }

        .clear-all-btn:hover {
            background-color: #ff7875;
        }

        .question-item {
            margin: 20px 0;
            padding: 15px;
            border: 1px solid #e8e8e8;
            border-radius: 8px;
        }

        .correct-answer-setting {
            margin: 15px 0;
            padding: 10px;
            background-color: #f5f5f5;
            border-radius: 4px;
        }

        .correct-answer-setting select {
            padding: 5px 10px;
            margin-left: 10px;
        }

        .answer-statistics {
            margin-top: 15px;
            padding: 10px;
            background-color: #f0f7ff;
            border-radius: 4px;
        }

        .answer-setting-item {
            margin: 15px 0;
            padding: 15px;
            border: 1px solid #e8e8e8;
            border-radius: 8px;
        }

        .answer-options {
            display: flex;
            justify-content: center;
            gap: 20px;
            margin-top: 10px;
        }

        .option-item {
            display: flex;
            align-items: center;
            padding: 8px 16px;
            border: 1px solid #d9d9d9;
            border-radius: 4px;
            cursor: pointer;
            transition: all 0.3s;
        }

        .option-item:hover {
            background-color: #f5f5f5;
        }

        .option-item input[type="radio"] {
            margin-right: 5px;
        }

        .option-item label {
            cursor: pointer;
        }

        .button-group {
            display: flex;
            justify-content: flex-end;
            gap: 10px;
            margin-top: 20px;
        }

        .submit-btn, .cancel-btn {
            padding: 8px 16px;
            border-radius: 4px;
            cursor: pointer;
        }

        .submit-btn {
            background-color: #1890ff;
            color: white;
            border: none;
        }

        .cancel-btn {
            background-color: #f5f5f5;
            border: 1px solid #d9d9d9;
        }

        .modal {
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            display: flex;
            justify-content: center;
            align-items: center;
            z-index: 1000;
        }

        .modal-content {
            background-color: white;
            padding: 20px;
            border-radius: 8px;
            max-width: 500px;
            width: 90%;
            max-height: 80vh;
            overflow-y: auto;
            position: fixed;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
        }
    </style>
</head>
<body>
    <div class="header">
        <h1>课堂管理</h1>
        
    </div>
    <div class="groups-container" id="groups-panel">
        <!-- 小组区域将通过JavaScript动态生成 -->
    </div>

    <button class="clear-all-btn" onclick="clearAllQuestions()">清空题目</button>
    <!--
    <div class="question-form">
        <h3>创建选择题</h3>
        <textarea id="question-content" placeholder="输入题目内容" rows="3"></textarea>
        <input type="text" id="option-a" placeholder="选项A">
        <input type="text" id="option-b" placeholder="选项B">
        <input type="text" id="option-c" placeholder="选项C">
        <input type="text" id="option-d" placeholder="选项D">
        <button onclick="createQuestion()">发布题目</button>
    </div>
-->
    <div style="position: fixed; bottom: 20px; left: 20px; display: flex; gap: 20px;">
        <button class="publish-questions-btn" onclick="showQuestionsDialog()">
            发布选择题
        </button>
        <button class="publish-questions-btn" onclick="showAnswerSettingPanel()">
            设置正确答案
        </button>
    </div>

    <div class="dialog-overlay" id="dialogOverlay"></div>

    <div class="questions-dialog" id="questionsDialog">
        <h2>发布选择题</h2>
        <div class="input-group">
            <label for="questionCount">要发布的题目数量：</label>
            <input 
                type="number" 
                id="questionCount" 
                min="1" 
                max="10" 
                value="1"
                placeholder="请输入题目数量（1-10）"
            >
        </div>
        <div class="dialog-buttons">
            <button class="dialog-btn cancel" onclick="closeQuestionsDialog()">取消</button>
            <button class="dialog-btn confirm" onclick="publishQuestions()">确认发布</button>
        </div>
    </div>

   

    <!-- 答案设置对话框 -->
    <div id="answerSettingPanel" class="modal" style="display: none;">
        <div class="modal-content">
            <h2>设置正确答案</h2>
            <div id="answerSettingContainer">
                <!-- 答案设置表单将在这里动态生成 -->
            </div>
            <div class="button-group">
                <button onclick="submitCorrectAnswers()" class="submit-btn">提交答案</button>
                <button onclick="closeAnswerSettingPanel()" class="cancel-btn">取消</button>
            </div>
        </div>
    </div>

    <script>
        const TOTAL_GROUPS = 8;

        function generateGroupCards() {
            const panel = document.getElementById('groups-panel');
            for (let i = 1; i <= TOTAL_GROUPS; i++) {
                const groupId = `group${i}`;
                const card = document.createElement('div');
                card.className = 'group-card';
                card.innerHTML = `
                    <h2>第${i}组</h2>
                    <div class="members-list" id="members-${groupId}">
                        <!-- 成员列表将通过JavaScript动态填充 -->
                    </div>
                `;
                panel.appendChild(card);
                loadGroupMembers(groupId);
            }
        }

        async function loadGroupMembers(groupId) {
            try {
                const response = await fetch(`/api/students/${groupId}`);
                const members = await response.json();
                
                // 获取当前活动的题目和答案
                const questionsResponse = await fetch('/api/questions/active');
                const activeQuestions = await questionsResponse.json();
                let answers = {};
                
                // 只有当有活动题目时才获取答案
                if (activeQuestions && activeQuestions.length > 0) {
                    // 获取所有题目的答案
                    for (const question of activeQuestions) {
                        const answersResponse = await fetch(`/api/answers/${question.id}`);
                        const questionAnswers = await answersResponse.json();
                        // 将答案按学生名字组织
                        questionAnswers.forEach(ans => {
                            if (!answers[ans.name]) {
                                answers[ans.name] = {};
                            }
                            answers[ans.name][question.id] = ans;
                        });
                    }
                }
                
                const membersList = document.getElementById(`members-${groupId}`);
                membersList.innerHTML = '';
                
                if (members.length > 0) {
                    const ul = document.createElement('ul');
                    ul.style.listStyle = 'none';
                    ul.style.padding = '0';
                    
                    members.forEach(member => {
                        const li = document.createElement('li');
                        li.className = 'member-item';
                        
                        // 显示该学生的所有答案
                        const studentAnswers = answers[member.name] || {};
                        const answerDisplay = activeQuestions && activeQuestions.length > 0 
                            ? `<div class="student-answers">
                                ${activeQuestions.map(q => {
                                    const answer = studentAnswers[q.id] || {};
                                    let answerClass = 'unanswered';
                                    if (answer.answer) {
                                        answerClass = answer.is_correct ? 'correct' : 'incorrect';
                                    }
                                    return `
                                        <span class="student-answer ${answerClass}"
                                              data-student="${member.name}"
                                              data-question="${q.id}">
                                            ${answer.answer || '-'}
                                        </span>`;
                                }).join(' ')}
                               </div>`
                            : '';
                        
                        li.innerHTML = `
                            <span class="student-name">${member.name}</span>
                            ${answerDisplay}
                            <button 
                                onclick="deleteStudent('${member.name}', '${member.group_id}')"
                                class="delete-btn"
                            >
                                删除
                            </button>
                        `;
                        ul.appendChild(li);
                    });
                    membersList.appendChild(ul);
                } else {
                    membersList.innerHTML += '<p>暂无成员</p>';
                }
            } catch (error) {
                console.error('加载成员列表失败:', error);
            }
        }

        async function deleteStudent(studentName, groupId) {
            try {
                const response = await fetch(`/api/students/${groupId}/${encodeURIComponent(studentName)}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                if (response.ok) {
                    loadGroupMembers(groupId);
                } else {
                    const errorData = await response.json();
                    throw new Error(errorData.detail || '删除失败');
                }
            } catch (error) {
                console.error('删除学生失败:', error);
                alert(`删除失败: ${error.message}`);
            }
        }

        async function startClass() {
            if (!confirm('确定要开始新的课程吗？')) {
                return;
            }

            try {
                const response = await fetch('/api/class/start', {
                    method: 'POST'
                });

                if (response.ok) {
                    alert('新课程已开始');
                    // 刷新所有小组的显示
                    for (let i = 1; i <= TOTAL_GROUPS; i++) {
                        loadGroupMembers(`group${i}`);
                    }
                } else {
                    throw new Error('开始课程失败');
                }
            } catch (error) {
                console.error('开始课程失败:', error);
                alert('开始课程失败，请重试');
            }
        }

        async function createQuestion() {
            const content = document.getElementById('question-content').value;
            const optionA = document.getElementById('option-a').value;
            const optionB = document.getElementById('option-b').value;
            const optionC = document.getElementById('option-c').value;
            const optionD = document.getElementById('option-d').value;

            if (!content || !optionA || !optionB || !optionC || !optionD) {
                alert('请填写完整的题目和选项');
                return;
            }

            try {
                const response = await fetch('/api/questions', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        content: content,
                        option_a: optionA,
                        option_b: optionB,
                        option_c: optionC,
                        option_d: optionD
                    })
                });

                if (response.ok) {
                    alert('题目发布成功');
                    // 清空表单
                    document.getElementById('question-content').value = '';
                    document.getElementById('option-a').value = '';
                    document.getElementById('option-b').value = '';
                    document.getElementById('option-c').value = '';
                    document.getElementById('option-d').value = '';
                } else {
                    throw new Error('发布题目失败');
                }
            } catch (error) {
                console.error('发布题目失败:', error);
                alert('发布题目失败，请重试');
            }
        }

        function showQuestionsDialog() {
            document.getElementById('dialogOverlay').style.display = 'block';
            document.getElementById('questionsDialog').style.display = 'block';
        }

        function closeQuestionsDialog() {
            document.getElementById('dialogOverlay').style.display = 'none';
            document.getElementById('questionsDialog').style.display = 'none';
        }

        async function publishQuestions() {
            const count = parseInt(document.getElementById('questionCount').value);
            
            if (isNaN(count) || count < 1 || count > 10) {
                alert('请输入1-10之间的数字');
                return;
            }

            try {
                const questions = [];
                for (let i = 0; i < count; i++) {
                    questions.push({
                        content: `第${i + 1}题`,
                        option_a: "A",
                        option_b: "B",
                        option_c: "C",
                        option_d: "D"
                    });
                }

                const response = await fetch('/api/questions/batch', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ questions })
                });

                if (!response.ok) {
                    throw new Error('发布题目失败');
                }

                alert(`成功发布了${count}道选择题`);
                closeQuestionsDialog();
            } catch (error) {
                console.error('发布题目失败:', error);
                alert('发布题目失败，请重试');
            }
        }

        async function clearAllQuestions() {
            if (!confirm('确定要清空所有题目和答题记录吗？此操作不可恢复！')) {
                return;
            }

            try {
                const response = await fetch('/api/questions/clear', {
                    method: 'POST'
                });

                if (response.ok) {
                    alert('已清空所有题目和答题记录');
                    // 刷新所有小组的显示
                    for (let i = 1; i <= TOTAL_GROUPS; i++) {
                        loadGroupMembers(`group${i}`);
                    }
                } else {
                    throw new Error('清空失败');
                }
            } catch (error) {
                console.error('清空题目失败:', error);
                alert('清空失败，请重试');
            }
        }

        // 设置正确答案
        async function setCorrectAnswer(questionId, answer) {
            try {
                const response = await fetch(`/api/questions/${questionId}/correct-answer`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        correct_answer: answer
                    })
                });

                if (response.ok) {
                    alert('正确答案设置成功');
                    // 刷新答题情况显示
                    updateAnswerDisplay(questionId);
                } else {
                    throw new Error('设置正确答案失败');
                }
            } catch (error) {
                console.error('设置正确答案失败:', error);
                alert('设置正确答案失败，请重试');
            }
        }

        // 更新答题情况显示
        async function updateAnswerDisplay(questionId) {
            try {
                const response = await fetch(`/api/answers/${questionId}`);
                const answers = await response.json();
                
                // 更新统计数据
                const totalStudents = document.getElementById('total-students');
                const answeredCount = document.getElementById('answered-count');
                const correctRate = document.getElementById('correct-rate');
                
                const answered = answers.length;
                const correct = answers.filter(a => a.is_correct).length;
                const rate = answered > 0 ? Math.round((correct / answered) * 100) : 0;
                
                answeredCount.textContent = answered;
                correctRate.textContent = rate;

                // 更新答案显示
                answers.forEach(answer => {
                    const answerElement = document.querySelector(
                        `.student-answer[data-student="${answer.name}"][data-question="${questionId}"]`
                    );
                    if (answerElement) {
                        answerElement.classList.remove('correct', 'incorrect', 'unanswered');
                        answerElement.classList.add(
                            answer.is_correct ? 'correct' : 'incorrect'
                        );
                        answerElement.textContent = `第${answer.question_number}题: ${answer.answer}`;
                    }
                });
            } catch (error) {
                console.error('更新答题情况失败:', error);
            }
        }

        // 显示答案设置面板
        async function showAnswerSettingPanel() {
            try {
                // 获取当前活动的题目
                const response = await fetch('/api/questions/active');
                if (!response.ok) {
                    throw new Error('获取题目失败');
                }
                
                const questions = await response.json();
                if (!questions || questions.length === 0) {
                    alert('当前没有活动的题目');
                    return;
                }

                console.log('Retrieved questions:', questions); // 调试日志

                const panel = document.getElementById('answerSettingPanel');
                const container = document.getElementById('answerSettingContainer');
                
                // 简化答案设置表单，只显示题号和ABCD选项
                container.innerHTML = questions.map((question, index) => `
                    <div class="answer-setting-item" data-question-id="${question.id}">
                        <p>第${index + 1}题</p>
                        <div class="answer-options">
                            <div class="option-item">
                                <input type="radio" 
                                    name="answer_${question.id}" 
                                    value="A" 
                                    id="answer_${question.id}_A"
                                >
                                <label for="answer_${question.id}_A">A</label>
                            </div>
                            <div class="option-item">
                                <input type="radio" 
                                    name="answer_${question.id}" 
                                    value="B" 
                                    id="answer_${question.id}_B"
                                >
                                <label for="answer_${question.id}_B">B</label>
                            </div>
                            <div class="option-item">
                                <input type="radio" 
                                    name="answer_${question.id}" 
                                    value="C" 
                                    id="answer_${question.id}_C"
                                >
                                <label for="answer_${question.id}_C">C</label>
                            </div>
                            <div class="option-item">
                                <input type="radio" 
                                    name="answer_${question.id}" 
                                    value="D" 
                                    id="answer_${question.id}_D"
                                >
                                <label for="answer_${question.id}_D">D</label>
                            </div>
                        </div>
                    </div>
                `).join('');

                // 为每个选项添加点击事件
                document.querySelectorAll('.option-item').forEach(item => {
                    item.addEventListener('click', function() {
                        const radio = this.querySelector('input[type="radio"]');
                        if (radio) {
                            radio.checked = true;
                        }
                    });
                });

                panel.style.display = 'block';
            } catch (error) {
                console.error('加载题目失败:', error);
                alert('加载题目失败，请重试');
            }
        }

        // 提交正确答案的函数
        async function submitCorrectAnswers() {
            try {
                const answerItems = document.querySelectorAll('.answer-setting-item');
                const answers = Array.from(answerItems).map(item => {
                    const questionId = item.dataset.questionId;
                    const selectedAnswer = item.querySelector('input[type="radio"]:checked');
                    
                    if (!selectedAnswer) {
                        return null;
                    }

                    return {
                        question_id: parseInt(questionId),
                        correct_answer: selectedAnswer.value
                    };
                }).filter(Boolean);

                if (answers.length === 0) {
                    alert('请至少设置一道题的答案');
                    return;
                }

                const response = await fetch('/api/questions/correct-answers/batch', {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ answers })
                });

                if (!response.ok) {
                    throw new Error('设置答案失败');
                }

                alert('正确答案设置成功');
                closeAnswerSettingPanel();

                // 重新加载所有小组的显示
                for (let i = 1; i <= TOTAL_GROUPS; i++) {
                    await loadGroupMembers(`group${i}`);
                }
            } catch (error) {
                console.error('提交答案失败:', error);
                alert('提交答案失败，请重试');
            }
        }

        // 关闭答案设置面板
        function closeAnswerSettingPanel() {
            document.getElementById('answerSettingPanel').style.display = 'none';
        }

        // 更新答题情况显示
        async function updateAnswerDisplay() {
            try {
                // 获取所有小组的答题情况
                for (let i = 1; i <= TOTAL_GROUPS; i++) {
                    await loadGroupMembers(`group${i}`);
                }
            } catch (error) {
                console.error('更新答题情况失败:', error);
            }
        }

        // 添加定期更新函数
        function startAutoUpdate() {
            // 每5秒更新一次显示
            setInterval(() => {
                for (let i = 1; i <= TOTAL_GROUPS; i++) {
                    loadGroupMembers(`group${i}`);
                }
            }, 5000);
        }

        // 页面加载时启动自动更新
        window.onload = function() {
            generateGroupCards();
            startAutoUpdate();
        };
    </script>
</body>
</html>